﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;
using System.ServiceModel;
using System.ComponentModel;

namespace TV4Home.Client.Desktop.QuickEPG.Pages
{
    /// <summary>
    /// Interaction logic for ChannelPage.xaml
    /// </summary>
    public partial class MainPage : Page
    {

        private ITVEInteraction tvWebClient = null;
        private BackgroundWorker channelWorker = new BackgroundWorker();

        private List<WebProgramBasic> _programs = null;
        private BackgroundWorker programWorker = new BackgroundWorker();
        private int channelId = 0;


        private List<WebSchedule> _schedules = null;
        public MainPage()
        {
            InitializeComponent();
            InitializeChannelData();

        }

        #region Channel
        private void InitializeChannelData()
        {
            ConnectToService();
            InitializeBackgroundWorker();
            if (!String.IsNullOrEmpty(Properties.Settings.Default.ServerName))
            {
                FetchChannelData();
            }
        }
        public void FetchChannelData()
        {
            Properties.Settings.Default.Reload();
            if (tvWebClient == null)
            {
                ConnectToService();
            }
            channelWorker.RunWorkerAsync();
        }
        private void InitializeBackgroundWorker()
        {
            channelWorker.DoWork += new DoWorkEventHandler(channelWorker_DoWork);
            channelWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(channelWorker_RunWorkerCompleted);
            programWorker.DoWork += new DoWorkEventHandler(programWorker_DoWork);
            programWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(programWorker_RunWorkerCompleted);

        }
        void channelWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                List<WebChannelBasic> channelList = e.Result as List<WebChannelBasic>;
                lbChannels.ItemsSource = channelList;
            }
        }
        void channelWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (tvWebClient != null)
            {
                e.Result = tvWebClient.GetChannelsBasic(Properties.Settings.Default.DefaultGroup);
            }
        }
        #endregion
        #region Programs



        private void FetchProgramData(int channelId)
        {
            this.channelId = channelId;
            programWorker.RunWorkerAsync();
        }

        void programWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                List<WebProgramBasic> programList = e.Result as List<WebProgramBasic>;
                lbPrograms.Items.Clear();
                int j = 0;
                foreach (WebProgramBasic program in programList)
                {

                    if (j >= 4)
                    {
                        break;
                    }
                    if (DateTime.Now > program.StartTime && DateTime.Now < program.EndTime)
                    {
                        j++;
                        MenuItem cmItem = new MenuItem();
                        ListBoxItem childItem = new ListBoxItem();
                        ContextMenu cMenu = new System.Windows.Controls.ContextMenu();
                        childItem.Background = new SolidColorBrush(Colors.Beige);

                        if (program.IsScheduled)
                        {
                            childItem.Background = new SolidColorBrush(Colors.Red);
                            cmItem.Header = "Stop Record";
                            cmItem.Click += new RoutedEventHandler(MenuItemStopRecord_Click);
                            cMenu.Items.Add(cmItem);
                        }
                        else
                        {
                            cmItem.Header = "Record Program";
                            cmItem.Click += new RoutedEventHandler(MenuItemRecordProgram_Click);
                            cMenu.Items.Add(cmItem);
                        }



                        childItem.ContextMenu = cMenu;
                        childItem.Tag = program;
                        childItem.Content = String.Format("{0} {1}", "Jetzt:", program.Title);
                        lbPrograms.Items.Add(childItem);



                    }

                    if (DateTime.Now < program.StartTime && program.StartTime.Date == DateTime.Today && program.StartTime <= DateTime.Now.AddHours(4))
                    {

                        j++;
                        MenuItem cmItem = new MenuItem();
                        ListBoxItem childItem = new ListBoxItem();
                        ContextMenu cMenu = new System.Windows.Controls.ContextMenu();


                        if (program.IsScheduled)
                        {
                            childItem.Background = new SolidColorBrush(Colors.Red);
                            cmItem.Header = "Stop Record";
                            cmItem.Click += new RoutedEventHandler(MenuItemStopRecord_Click);
                            cMenu.Items.Add(cmItem);
                        }
                        else
                        {
                            cmItem.Header = "Record Program";
                            cmItem.Click += new RoutedEventHandler(MenuItemRecordProgram_Click);
                            cMenu.Items.Add(cmItem);
                        }

                        childItem.ContextMenu = cMenu;
                        childItem.Tag = program;
                        childItem.Content = String.Format("{0}{1} {2}", program.StartTime.TimeOfDay, ":", program.Title);
                        lbPrograms.Items.Add(childItem);
                    }
                }             
            }
        }

        void programWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (tvWebClient != null)
            {
                if (channelId > 0)
                {
                    e.Result = tvWebClient.GetProgramsBasicForChannel(channelId, DateTime.Now, DateTime.Now.AddHours(8));
                }
            }
        }
        #endregion

        #region UIEventHandler
        private void lbChannels_Selected(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is ListBoxItem)
            {
                if (((ListBoxItem)e.OriginalSource).Content is WebChannelBasic)
                {
                    WebChannelBasic channel = ((ListBoxItem)e.OriginalSource).Content as WebChannelBasic;
                    if (channel != null)
                    {
                        FetchProgramData(channel.IdChannel);
                    }
                }
            }
        }
        void MenuItemRecordProgram_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem)
            {
                MenuItem contextMenuItem = (MenuItem)sender;

                if (contextMenuItem.Parent is ContextMenu)
                {
                    ContextMenu contextMenu = (ContextMenu)contextMenuItem.Parent;

                    if (contextMenu.PlacementTarget is ListBoxItem)
                    {
                        ListBoxItem originatingItem = (ListBoxItem)contextMenu.PlacementTarget;

                        if (originatingItem.Tag is WebProgramBasic)
                        {
                            WebProgramBasic program = (WebProgramBasic)originatingItem.Tag;

                            try
                            {

                                tvWebClient.AddScheduleDetailed(program.IdChannel, program.Title, program.StartTime, program.EndTime, 0, Properties.Settings.Default.TimeBeforeSchedule, Properties.Settings.Default.TimeAfterSchedule, "", 0);
                                MenuItem cmItem = new MenuItem();
                                cmItem.Header = "Stop Record";
                                cmItem.Click += new RoutedEventHandler(MenuItemStopRecord_Click);

                                originatingItem.ContextMenu.Items[0] = cmItem;
                                originatingItem.Background = new SolidColorBrush(Colors.Red);



                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error while adding schedule, please check your WebServices connection" + ex.Message);
                            }

                        }
                    }
                }
            }
        }
        void MenuItemStopRecord_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem)
            {
                MenuItem contextMenuItem = (MenuItem)sender;

                if (contextMenuItem.Parent is ContextMenu)
                {
                    ContextMenu contextMenu = (ContextMenu)contextMenuItem.Parent;

                    if (contextMenu.PlacementTarget is ListBoxItem)
                    {
                        ListBoxItem originatingItem = (ListBoxItem)contextMenu.PlacementTarget;

                        if (originatingItem.Tag is WebProgramBasic)
                        {
                            WebProgramBasic program = (WebProgramBasic)originatingItem.Tag;
                            if (tvWebClient == null)
                            {
                                ConnectToService();
                            }
                            if (tvWebClient != null)
                            {
                                _schedules = tvWebClient.GetSchedules();

                                foreach (WebSchedule schedule in _schedules)
                                {
                                    if (schedule.IdChannel == program.IdChannel && schedule.StartTime == program.StartTime)
                                    {
                                        try
                                        {
                                            tvWebClient.CancelSchedule(program.IdProgram);

                                            MenuItem cmItem = new MenuItem();
                                            cmItem.Header = "Record Program";
                                            cmItem.Click += new RoutedEventHandler(MenuItemRecordProgram_Click);

                                            originatingItem.ContextMenu.Items[0] = cmItem;
                                            originatingItem.Background = new SolidColorBrush(Colors.White);


                                        }
                                        catch (Exception ex)
                                        {
                                            MessageBox.Show("Error while deleting schedule, please check your WebServices connection" + ex.Message);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region Service
        private void ConnectToService()
        {
            //Connects to the tv4home webservice by netpipe
            try
            {
                tvWebClient = Connect();
            }
            catch (Exception ex)
            {
                //if connection is not possible ask whether it retry or not
                string sMessageBoxText = "Couldn't connect. Try again?";
                string sCaption = "QuickEPG";

                MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

                MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);
                // Process message box results
                switch (rsltMessageBox)
                {

                    case MessageBoxResult.Yes:
                        ConnectToService();
                        break;
                    case MessageBoxResult.No:
                        MessageBox.Show(ex.ToString());
                        break;
                }
            }

        }
        private ITVEInteraction Connect()
        {
            if (!String.IsNullOrEmpty(Properties.Settings.Default.ServerName))
            {
                switch (Properties.Settings.Default.IsIntranet)
                {
                    case true:
                        return ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, Properties.Settings.Default.ServerName)));
                    case false:
                        return ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.InternetUrl, Properties.Settings.Default.ServerName)));
                }
            }

            return null;
        }
        #endregion

    }
}
